<?php
namespace App\Supports\Sms;

use App\Models\User;
use Cache;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Jobs\SmsSendingJob;
use Illuminate\Support\Collection;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class Sms
{
	protected $phone;

	protected $template = '';

	/**
	 * @var Collection
	 * ['code' => '0000']
	 */
	protected $data;

	public function phone($phone)
	{
		$this->phone = $phone;
		return $this;
	}

	public function template($template)
	{
		$this->template = $template;
		return $this;
	}

	public function data(...$data): self
	{
		if (app()->environment('production')) {
			$this->data = collect(['code', '0000']);
			//$this->data = collect($data)->flatten();
		} else {
			$this->data = collect(['code', '0000']);
		}
		return $this;
	}

	public function send(): Collection
	{
		if (app()->environment('production')) {
			dispatch(new SmsSendingJob($this));
		}
        $this->updateUserReset();
		return $this->cacheDataAfterSent();
	}

	public function emit()
	{
		try {
			app('easysms')->send($this->phone, [
				'template' => $this->template,
				'data'     => ['code' => $this->data->last()]
			]);
            $this->updateUserReset();
		} catch (NoGatewayAvailableException $exception) {
			$message = $exception->getException('aliyun')->getMessage();
			Log::info($message);
		}
	}

    protected function updateUserReset()
    {
        if ($this->template == 'SMS_214420078') {
            User::where('phone', $this->phone)->update([
                'password_reset_sms_at' => Carbon::now()
            ]);
        }
    }

	protected function cacheDataAfterSent(): Collection
	{
		$key = 'sms_'.Str::random(15);
		$expiredAt = now()->addMinutes(3);
		Cache::put($key, ['phone' => $this->phone, 'variable' => $this->data->last()], $expiredAt);
		return collect(['sms_key' => $key, 'expired_at' => $expiredAt->toDateTimeString()]);
	}

	public function isSmsDataRight($key, $phone, $variable): bool
	{
		/**
		 * Comparing whether sms variable submitted
		 * is equal to cached sms variable.
		 */
		
		if ($data = Cache::get($key)) {
			return $data['phone'] == $phone and hash_equals($data['variable'], $variable);
		}
		return false;
	}

	public function cleanCachedDataAfterUsing($key)
	{
		Cache::forget($key);
	}
}
